package com.zues.daiommiddleware.controller;

import com.zues.daiommiddleware.config.AliyunVideoProperties;
import com.zues.daiommiddleware.linstener.SpeechSocketListener;
import com.zues.daiommiddleware.result.HttpStatus;
import com.zues.daiommiddleware.service.SpeechTranscriberService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Objects;


@RestController
@RequestMapping("speech")
@Slf4j
@RequiredArgsConstructor
public class SpeechController {

    private final WebSocketServer webSocketServer;

    private final AliyunVideoProperties videoProperties;

    private SpeechTranscriberService speechTranscriberService;

    @GetMapping("start/{userId}")
    public int start(@PathVariable String userId) {
        try {
            speechTranscriberService = new SpeechTranscriberService(videoProperties.getAppKey(), videoProperties.getAccessToken());
//            if (!webSocketServer.isOnline(userId)) {
//                log.error("当前用户未创建连接");
//                throw new RuntimeException("当前用户未创建连接");
//            }
            SpeechSocketListener listener = new SpeechSocketListener(webSocketServer, userId);
            //开启识别
            speechTranscriberService.process(listener);
            return HttpStatus.SUCCESS;
        } catch (Exception e) {
            e.printStackTrace();
            return HttpStatus.ERROR;
        }
    }

    @GetMapping("stop")
    public int stop() {
        if (Objects.isNull(speechTranscriberService)) {
            log.error("当前没有开启识别服务");
            return HttpStatus.ERROR;
        }
        try {
            // 关闭服务实例
            speechTranscriberService.shutdown(speechTranscriberService);
            return HttpStatus.SUCCESS;
        } catch (Exception e) {
            e.printStackTrace();
            return HttpStatus.ERROR;
        }
    }

}
